---
title: 'Amazon Cognito Authentication: Cypress Guide'
sidebar_label: 'Amazon Cognito Authentication'
description: 'Implement Amazon Cognito authentication in Cypress. Securely manage authentication processes for Cypress end-to-end testing scenarios'
---

<ProductHeading product="app" />

# Amazon Cognito Authentication

:::info

##### <Icon name="question-circle" color="#4BBFD2" /> What you'll learn

- How to implement Amazon Cognito authentication in Cypress
- How to securely manage authentication processes for Cypress end-to-end testing scenarios

:::

Amazon [Cognito](https://aws.amazon.com/cognito) is an authentication provider
apart of [Amazon Web Services (AWS)](https://aws.amazon.com).

The documentation for [Amazon Cognito](https://aws.amazon.com/cognito)
recommends using the
[AWS Amplify Framework Authentication Library](https://aws-amplify.github.io/amplify-js/api/classes/authclass.html)
from the [AWS Amplify Framework](https://aws.amazon.com/amplify/framework/) to
interact with a deployed [Amazon Cognito](https://aws.amazon.com/cognito)
instance. Using the
[AWS Amplify Framework Authentication Library](https://aws-amplify.github.io/amplify-js/api/classes/authclass.html),
we are able to programmatically drive the creation and authentication of users
against a fully deployed back end.

This guide illustrates the limited code from the
[AWS Amplify Framework](https://aws.amazon.com/amplify/framework/) needed to
programmatically log an existing a user into an application.

<Tabs>

  <TabItem value="v5" label="Amplify v5.x.x" default>

```jsx
// Add 'aws-amplify' library into your application
import Amplify, { Auth } from 'aws-amplify'

// Configure Auth category with your Amazon Cognito credentials
Amplify.configure({
  Auth: {
    identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX', // Amazon Cognito Identity Pool ID
    region: 'XX-XXXX-X', // Amazon Cognito Region
  },
})

// Call Auth.signIn with user credentials
Auth.signIn(username, password)
  .then((user) => console.log(user))
  .catch((err) => console.log(err))
```

  </TabItem>

  <TabItem value="v6" label="Amplify v6.x.x">

```tsx
import { Amplify } from "aws-amplify";
import { fetchAuthSession, signIn } from "aws-amplify/auth";

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolId: "XX-XXXX-X_XXXXXXXXX",
      userPoolClientId: "XXXXXXXXXXXXXXXXXXXXXXXXX",
      // OR:
      identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX', // Amazon Cognito Identity Pool ID
    },
  },
});
signIn({ username, password, { authFlowType: "USER_PASSWORD_AUTH" } })
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  .then((_signInOutput) => fetchAuthSession())
  .then((authSession) => console.log(authSession))
  .catch((err) => console.log(err));
```

  </TabItem>

</Tabs>

## Amazon Cognito Setup

If not already setup, you will need to
[create an account](https://docs.amplify.aws/start/getting-started/installation/q/integration/react#sign-up-for-an-aws-account)
with [Amazon Web Services (AWS)](https://aws.amazon.com).

An [Amazon Cognito](https://aws.amazon.com/cognito) integration is available in
the

<Icon name="github" inline="true" contentType="rwa" />. Clone the Cypress Real
World App and install the [AWS Amazon Amplify CLI](https://docs.amplify.aws/cli)
as follows:

```jsx
npm install @aws-amplify/cli --global
```

The

<Icon name="github" inline="true" contentType="rwa" /> is configured with an optional
[Amazon Cognito](https://aws.amazon.com/cognito) instance via the [AWS Amplify Framework
Authentication Library](https://aws-amplify.github.io/amplify-js/api/classes/authclass.html).
The [AWS Amazon Amplify CLI](https://docs.amplify.aws/cli) is used to provision the
[Amazon Web Services (AWS)](https://aws.amazon.com) infrastructure needed to configure
your environment and cloud resources.

First, run the
[amplify init](https://docs.amplify.aws/cli/start/workflows#initialize-new-project)
command to initialize the
Real World App.
This will provision the project with your [AWS](https://aws.amazon.com)
credentials.

```jsx
amplify init
```

Next, run the
[amplify push](https://docs.amplify.aws/cli/start/workflows#amplify-push)
command to create the [Amazon Cognito](https://aws.amazon.com/cognito) resources
in the cloud:

```jsx
amplify push
```

:::info

<strong>Note</strong>

Use the `yarn dev:cognito` command when starting the
Real World App.

:::

## Setting Amazon Cognito app credentials in Cypress

First, we need to configure Cypress to use the
[AWS Cognito](https://aws.amazon.com/cognito) environment variables set in the
`.env` file. In addition, we are using the `aws-exports.js` supplied during the
[AWS Amplify CLI](https://docs.amplify.aws/cli) build process.

:::cypress-config-example

```ts
// Populate process.env with values from .env file
require('dotenv').config()
// AWS exports
const awsConfig = require('./aws-exports-es5.js')
```

```js
{
  env: {
    cognito_username: process.env.AWS_COGNITO_USERNAME,
    cognito_password: process.env.AWS_COGNITO_PASSWORD,
    awsConfig: awsConfig.default
  }
}
```

:::

## Custom Command for Amazon Cognito Authentication

There are two ways you can authenticate to AWS Cognito:

- [Login with `cy.origin()`](/app/guides/authentication-testing/amazon-cognito-authentication#Login-with-cyorigin)
- [Programmatic Access](/app/guides/authentication-testing/amazon-cognito-authentication#Programmatic-Login)

### Login with [`cy.origin()`](/api/commands/origin)

We'll write a custom command called `loginByCognito` to perform a login to
[Amazon Cognito](https://aws.amazon.com/cognito). This command will use
[`cy.origin()`](/api/commands/origin) to

1. Navigate to the Cognito origin
2. Input user credentials
3. Sign in and redirect back to the
   <Icon name="github" inline="true" contentType="rwa" />
4. Cache the results with [`cy.session()`](/api/commands/session)

```jsx title="cypress/support/auth-provider-commands/cognito.ts"
// Amazon Cognito
const loginToCognito = (username: string, password: string) => {
  Cypress.log({
    displayName: 'COGNITO LOGIN',
    message: [`🔐 Authenticating | ${username}`],
    autoEnd: false,
  })

  cy.visit('/')

  cy.origin(
    Cypress.env('cognito_domain'),
    {
      args: {
        username,
        password,
      },
    },
    ({ username, password }) => {
      cy.contains('Sign in with your email and password')
      // Cognito log in page has some elements of the same id but are off screen.
      // We only want the visible elements to log in
      cy.get('input[name="username"]:visible').type(username)
      cy.get('input[name="password"]:visible').type(password, {
        // use log: false to prevent your password from showing in the Command Log
        log: false,
      })
      cy.get('input[name="signInSubmitButton"]:visible').click()
    }
  )

  // give a few seconds for redirect to settle
  cy.wait(2000)

  // verify we have made it passed the login screen
  cy.contains('Get Started').should('be.visible')
}

// right now our custom command is light. More on this later!
Cypress.Commands.add('loginByCognito', (username, password) => {
  return loginToCognito(username, password)
})
```

Now, we can use our `loginByCognito` command in the test. Below is our test to
login as a user via [Amazon Cognito](https://aws.amazon.com/cognito), complete
the onboarding process and logout.

:::info

The
[runnable version of this test](https://github.com/cypress-io/cypress-realworld-app/blob/develop/cypress/tests/ui-auth-providers/cognito.spec.ts)
is in the

<Icon name="github" inline="true" contentType="rwa" />.

:::

```jsx title="auth.spec.js"
describe('Cognito, cy.origin() login', function () {
  beforeEach(function () {
    // Seed database with test data
    cy.task('db:seed')

    // login via Amazon Cognito via cy.origin()
    cy.loginByCognito(
      Cypress.env('cognito_username'),
      Cypress.env('cognito_password')
    )
  })

  it('shows onboarding', function () {
    cy.contains('Get Started').should('be.visible')
  })
})
```

<DocsVideo
  src="https://vimeo.com/789093851"
  title="AWS Cognito Authentication with cy.origin()"
/>

Now, we can refactor our login command to take advantage of
[`cy.session()`](/api/commands/session) to store our logged in user so we don't
have to reauthenticate with every test.

```jsx title="cypress/support/auth-provider-commands/cognito.ts"
// Amazon Cognito
Cypress.Commands.add(
  'loginByCognito, cy.origin() login',
  (username, password) => {
    cy.session(
      `cognito-${username}`,
      () => {
        return loginToCognito(username, password)
      },
      {
        validate() {
          cy.visit('/')
          // revalidate our session to make sure we are logged in
          cy.contains('Get Started').should('be.visible')
        },
      }
    )
  }
)
```

<DocsVideo
  src="https://vimeo.com/789093817"
  title="AWS Cognito Authentication with cy.session()"
/>

### Programmatic Login

Next, we'll write a command to perform a programmatic login into
[Amazon Cognito](https://aws.amazon.com/cognito) and set items in `localStorage`
with the authenticated users details, which we will use in our application code
to verify we are authenticated under test.

In this `loginByCognitoApi` command, we call `Auth.signIn`, then use that
response to set the items inside of localStorage for the UI to know that our
user is logged into the application.

<Tabs>

  <TabItem value="v5" label="Amplify v5.x.x" default>

```jsx title="cypress/support/auth-provider-commands/cognito.ts"
import Amplify, { Auth } from 'aws-amplify'

Amplify.configure(Cypress.env('awsConfig'))

// Amazon Cognito
Cypress.Commands.add('loginByCognitoApi', (username, password) => {
  const log = Cypress.log({
    displayName: 'COGNITO LOGIN',
    message: [`🔐 Authenticating | ${username}`],
    // @ts-ignore
    autoEnd: false,
  })

  log.snapshot('before')

  const signIn = Auth.signIn({ username, password })

  cy.wrap(signIn, { log: false }).then((cognitoResponse) => {
    const keyPrefixWithUsername = `${cognitoResponse.keyPrefix}.${cognitoResponse.username}`

    window.localStorage.setItem(
      `${keyPrefixWithUsername}.idToken`,
      cognitoResponse.signInUserSession.idToken.jwtToken
    )

    window.localStorage.setItem(
      `${keyPrefixWithUsername}.accessToken`,
      cognitoResponse.signInUserSession.accessToken.jwtToken
    )

    window.localStorage.setItem(
      `${keyPrefixWithUsername}.refreshToken`,
      cognitoResponse.signInUserSession.refreshToken.token
    )

    window.localStorage.setItem(
      `${keyPrefixWithUsername}.clockDrift`,
      cognitoResponse.signInUserSession.clockDrift
    )

    window.localStorage.setItem(
      `${cognitoResponse.keyPrefix}.LastAuthUser`,
      cognitoResponse.username
    )

    window.localStorage.setItem('amplify-authenticator-authState', 'signedIn')
    log.snapshot('after')
    log.end()
  })

  cy.visit('/')
})
```

  </TabItem>

  <TabItem value="v6" label="Amplify v6.x.x">

```tsx title="cypress/support/auth-provider-commands/cognito.ts"
import { Amplify } from 'aws-amplify'
import { fetchAuthSession, signIn } from 'aws-amplify/auth'

Amplify.configure(Cypress.env('awsConfig'))
const fetchJwts = async (username: string, password: string) => {
  const options = { authFlowType: 'USER_PASSWORD_AUTH' as const }
  await signIn({ username, password, options })
  const authSession = await fetchAuthSession()
  const tokens = authSession.tokens!
  const accessToken = tokens.accessToken
  const accessTokenPayload = accessToken.payload
  return {
    idToken: tokens.idToken!.toString(),
    accessToken: accessToken.toString(),
    clientId: accessTokenPayload.client_id as string,
    accessTokenSub: accessTokenPayload.sub!,
  }
}
type JwtResponse = Awaited<ReturnType<typeof fetchJwts>>

// Amazon Cognito
Cypress.Commands.add(
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  'loginByCognitoApi',
  (username: string, password: string) => {
    const log = Cypress.log({
      displayName: 'COGNITO LOGIN',
      message: [`🔐 Authenticating | ${username}`],
      autoEnd: false,
    })

    log.snapshot('before')

    cy.wrap(fetchJwts(username, password), { log: false }).then(
      (unknownJwts) => {
        const { idToken, accessToken, clientId, accessTokenSub } =
          unknownJwts as JwtResponse

        const keyPrefix = `CognitoIdentityServiceProvider.${clientId}`
        const keyPrefixWithUsername = `${keyPrefix}.${accessTokenSub}`

        const ls = window.localStorage
        ls.setItem(`${keyPrefixWithUsername}.idToken`, idToken)
        ls.setItem(`${keyPrefixWithUsername}.accessToken`, accessToken)
        ls.setItem(`${keyPrefix}.LastAuthUser`, accessTokenSub)

        log.snapshot('after')
        log.end()
      }
    )
  }
)
```

  </TabItem>

</Tabs>

Finally, we can use our `loginByCognitoApi` command in at test. Below is our
test to login as a user via [Amazon Cognito](https://aws.amazon.com/cognito),
complete the onboarding process and logout.

:::info

The
[runnable version of this test](https://github.com/cypress-io/cypress-realworld-app/blob/develop/cypress/tests/ui-auth-providers/cognito.spec.ts)
is in the <Icon name="github" inline="true" contentType="rwa" />.

:::

```jsx
describe('Cognito, programmatic login', function () {
  beforeEach(function () {
    // Seed database with test data
    cy.task('db:seed')

    // Programmatically login via Amazon Cognito API
    cy.loginByCognitoApi(
      Cypress.env('cognito_username'),
      Cypress.env('cognito_password')
    )
  })

  it('shows onboarding', function () {
    cy.contains('Get Started').should('be.visible')
  })
})
```

### Adapting an Amazon Cognito App for Testing

:::info

<strong>AWS Backend Services Need No Adaptation</strong>

Often times, AWS Cognito is used when other AWS services provide the backend,
such as AWS AppSync for GraphQL APIs or AWS API Gateway for REST APIs. These
backend services can be configured to verify cognito JWTs without additional
code. However, if you are hosting a webserver backend, like the [cypress
real-world app](https://github.com/cypress-io/cypress-realworld-app) does with
the Express npm library, it must be adapted, as the real-world app is, to verify
the Cognito JWTs to authorize the frontend's requests.

:::

The

<Icon name="github" inline="true" contentType="rwa" /> is used and provides configuration
and runnable code for both the React SPA and the Express back end.

The front end uses the
[AWS Amplify Framework Authentication Library](https://aws-amplify.github.io/amplify-js/api/classes/authclass.html).
The back end uses the [express-jwt](https://github.com/auth0/express-jwt) to
validate JWTs from [Amazon Cognito](https://aws.amazon.com/cognito).

#### Adapting the back end

In order to validate API requests from the frontend, we install
[express-jwt](https://github.com/auth0/express-jwt) and
[jwks-rsa](https://github.com/auth0/node-jwks-rsa) and configure validation for
JWT's from [Amazon Cognito](https://aws.amazon.com/cognito).

<Tabs>

  <TabItem value="v5" label="Amplify v5.x.x" default>

```jsx title="backend/helpers.ts"
// ... initial imports
import jwt from 'express-jwt'
import jwksRsa from 'jwks-rsa'

// ...

const awsCognitoJwtConfig = {
  secret: jwksRsa.expressJwtSecret({
    jwksUri: `https://cognito-idp.${awsConfig.aws_cognito_region}.amazonaws.com/${awsConfig.aws_user_pools_id}/.well-known/jwks.json`,
  }),

  issuer: `https://cognito-idp.${awsConfig.aws_cognito_region}.amazonaws.com/${awsConfig.aws_user_pools_id}`,
  algorithms: ['RS256'],
}

export const checkCognitoJwt = jwt(awsCognitoJwtConfig).unless({
  path: ['/testData/*'],
})
```

  </TabItem>

  <TabItem value="v6" label="Amplify v6.x.x">

```jsx title="backend/helpers.ts"
// ... initial imports
import jwt from 'express-jwt'
import jwksRsa from 'jwks-rsa'

// ...
const userPoolId = awsConfig.Auth.Cognito.userPoolId
const region = userPoolId.split('_')[0]
const awsCognitoJwtConfig = {
  secret: jwksRsa.expressJwtSecret({
    jwksUri: `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`,
  }),

  issuer: `https://cognito-idp.${region}.amazonaws.com/${userPoolId}`,
  algorithms: ['RS256'],
}

export const checkCognitoJwt = jwt(awsCognitoJwtConfig).unless({
  path: ['/testData/*'],
})
```

  </TabItem>

</Tabs>

Once this helper is defined, we can use globally to apply to all routes:

```jsx title="backend/app.ts"
// initial imports ...
import { checkCognitoJwt } from './helpers'

// ...

if (process.env.REACT_APP_AWS_COGNITO) {
  app.use(checkCognitoJwt)
}

// routes ...
```

#### Adapting the front end

We need to update our front end React app to allow for authentication with
[Amazon Cognito](https://aws.amazon.com/cognito) using the
[AWS Amplify Framework Authentication Library](https://aws-amplify.github.io/amplify-js/api/classes/authclass.html).

First, we create a `AppCognito.tsx` container, based off of the `App.tsx`
component.

A `useEffect` hook is added to get the access token for the authenticated user
and send a `COGNITO` event with the token to work with the existing authentication
layer (`authMachine.ts`). If no access token is yet available, we redirect the
browser to the [Amazon Cognito](https://aws.amazon.com/cognito) User Pool Hosted UI
to provide the login form.

<Tabs>
  <TabItem value="v6" label="Amplify v6.x.x">

```jsx title="src/containers/AppCognito.tsx"
// amplify v6
// initial imports ...
import { Amplify, ResourcesConfig } from "aws-amplify";
import { fetchAuthSession, signInWithRedirect, signOut } from "aws-amplify/auth";

import awsConfig from "../aws-exports";

Amplify.configure(awsConfig as ResourcesConfig);

// ...

const AppCognito: React.FC = () => {

  // ...

  useEffect(() => {
    if (!isLoggedIn) {
      fetchAuthSession().then((authSession) => {
        if (authSession && authSession.tokens && authSession.tokens.accessToken) {
          const { tokens, userSub } = authSession;
          authService.send("COGNITO", {
            accessTokenJwtString: tokens!.accessToken.toString(),
            userSub: userSub!,
            email: tokens!.idToken!.payload.email,
          });
        } else {
          void signInWithRedirect();
        }
      });
    }
  }, [isLoggedIn]);

  // ...

  if (!isLoggedIn) {
    return null; // redirection will occur soon anyway
  }
};

export default AppCognito;
```

  </TabItem>

</Tabs>

:::tip

<strong>Try it out</strong>

The complete
[AppCognito.tsx component](https://github.com/cypress-io/cypress-realworld-app/blob/develop/src/containers/AppCognito.tsx)
is in the <Icon name="github" inline="true" contentType="rwa" />.

:::

Next, we update our entry point (`index.tsx`) to use our `AppCognito.tsx`
component.

```jsx title="src/index.tsx"
// ... initial imports
import AppCognito from './containers/AppCognito'

// ...

if (process.env.REACT_APP_AWS_COGNITO) {
  ReactDOM.render(
    <Router history={history}>
      <ThemeProvider theme={theme}>
        <AppCognito />
      </ThemeProvider>
    </Router>,
    document.getElementById('root')
  )
}
```
